const express = require("express");
const { File, sequelize } = require("../models");
const { success, fail } = require("../utils/response");
const { NotFound, BadRequest, Unauthorized } = require("http-errors");
const { singleImgUpload, moreImgsUpload, ossSdk } = require("../utils/aliyun-oss");
const router = express.Router();

// 查询文件-带分页
router.get("/", async (req, res) => {
  try {
    const { pageNum, pageSize } = req.query;
    const conditions = getConditions(req);
    const userId = req.user?.userId
    // 前台只能查自己上传的文件
    conditions.where.userId = userId
    const { count, rows } = await File.findAndCountAll(conditions);
    success(res, "获取成功", {
      pageNum,
      pageSize,
      count,
      list: rows,
    });
  } catch (error) {
    // console.log("自主抛出的错误！", error.name);
    fail(res, error);
  }
});
// 获取参数
function getConditions(req) {
  const { keywords, pageNum, pageSize } = req.query;
  const conditions = {
    where: {},
  };
  // 分页参数，没传分页 就是查询所有
  const page = Math.abs(pageNum);
  const size = Math.abs(pageSize);
  if (page && size) {
    conditions.offset = (page - 1) * size;
    conditions.limit = size;
  }
  // 处理普通参数
  if (keywords) {
    conditions.where.originalname = {
      [Op.like]: `%${keywords}%`,
    };
  }
  return conditions;
}
// 上传单图片
router.post("/img", (req, res) => {
  singleImgUpload(req, res, async err => {
    try {
      const userId = req.user?.userId
      if (err) {
        fail(res, err);
      } else {
        console.log("req.user", req.user);
        // if(!req.user?.userId) {
        //   throw new Unauthorized("请先登录");
        // }
        const param = {
          ...req.file,
          userId: userId,
          fullName: req.file.path + req.file.filename,
        };
        const row = await File.create(param);
        success(res, "上传成功！", row);
      }
    } catch (error) {
      fail(res, error);
    }
  });
});
// 上传多图片
router.post("/imgs", (req, res) => {
  moreImgsUpload(req, res, async err => {
    try {
      const userId = req.user?.userId
      if (err) {
        fail(res, err);
      } else {
        if(req.files && req.files.length>0) {
          for(let file of req.files) {
            const param = {
              ...file,
              userId: userId,
              fullName: file.path + file.filename,
            };
            await File.create(param);
          }
        }
        success(res, "上传成功！", req.files);
      }
    } catch (error) {
      fail(res, error);
    }
  });
});
// 删除文件
router.delete("/:id", async (req, res) => {
  const transaction = await sequelize.transaction()
  try {
    const id = req.params.id;
    const userId = req.user?.userId
    if (!id) {
      throw new BadRequest("缺少id");
    }
    const file = await File.findOne({
      where: {
        id,
        userId
      }
    })
    if (!file) {
      throw new NotFound("未找到此文件");
    }
    const result = await ossSdk.delete(file?.fullName)
    console.log(result);
    const row = await file.destroy(
      {transaction}
    )
    await transaction.commit()
    success(res, "success");
  } catch (error) {
    await transaction.rollback()
    fail(res, error);
  }
});
// 删除多个文件
router.post("/deleteFiles", async (req, res) => {
  const transaction = await sequelize.transaction()
  try {
    const {fileKeys} = req.body;
    console.log('fileKeys==', fileKeys);
    const userId = req.user?.userId
    if (!fileKeys || !Array.isArray(fileKeys)) {
      throw new BadRequest("fileKeys 需要是数组");
    }
    const files = await File.findAll({
      where: {
        id: fileKeys,
        userId
      },
    });
    if (!files || files?.length === 0) {
      throw new NotFound("未找到这些文件");
    }
    // 删除oss中的文件
    const fullNameArr = files?.map(item => item.fullName || '')
    const result = await ossSdk.deleteMulti(fullNameArr)
    console.log(result);
    // 删除数据库文件
    const deleteCount = await File.destroy({
      where: {
        id: fileKeys,
        userId
      },
      transaction
    })
    await transaction.commit()
    success(res, "success", deleteCount);
  } catch (error) {
    await transaction.rollback()
    fail(res, error);
  }
});

module.exports = router;
